package cn.jantd.modules.system.controller;


import cn.jantd.core.annotation.AutoLog;
import cn.jantd.core.api.vo.Result;
import cn.jantd.core.system.query.QueryGenerator;
import cn.jantd.core.system.vo.LoginUser;
import cn.jantd.core.util.RedisUtil;
import cn.jantd.core.util.oConvertUtils;
import cn.jantd.modules.system.entity.*;
import cn.jantd.modules.system.model.SysDepartTreeModel;
import cn.jantd.modules.system.service.*;
import cn.jantd.modules.system.vo.SerServerDpartVO;
import cn.jantd.modules.system.vo.SysLogDpartVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zstack.sdk.StopVmInstanceAction;
import org.zstack.sdk.ZSClient;
import org.zstack.sdk.ZSConfig;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 服务表 前端控制器
 * </p>
 *
 * @Author xiagf
 * @date 2019-07-04
 */
@RestController
@RequestMapping("/sys/myserver")
@Slf4j
public class SerServerController {
    @Autowired
    private ISerServerService serServerService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISerVirtualService serVirtualService;
    @Autowired
    private ISysUserDepartService sysUserDepartService;
    @Autowired
    private ISysDepartService sysDepartService;
    /*    public String loginuser() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("输出一下数据是什么：++++++++="+sysUser.getUsername());
        String user=sysUser.getUsername();
        return user;
    }*/
  /*  public Result<List<LoginUser>> loginuser() {
        Result<List<LoginUser>> result = new Result<>();

        LoginUser user=new LoginUser();
        ArrayList<LoginUser> arrayList = new ArrayList<LoginUser>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("输出一下数据是什么：++++++++="+sysUser.getUsername());
        user.setUsername(sysUser.getUsername());
        arrayList.add(user);
        result.setResult(arrayList);
        System.out.println(arrayList);
        result.setSuccess(true);
        return result;
    }*/

    /**
     * @param server
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     * @功能：查询申请服务列表
     */
    @AutoLog(value = "服务管理-分页查询申请服务记录")
    @ApiOperation(value = "服务管理-分页查询申请服务记录")
    @GetMapping(value = "/list")
    public Result<IPage<SerServerDpartVO>> queryPageList(SerServer server, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("看看sysuser是什么：++++++++++++++"+sysUser);
        Result<IPage<SerServerDpartVO>> result = new Result<>();
        QueryWrapper<SerServer> queryWrapper = QueryGenerator.initQueryWrapper(server, req.getParameterMap());
        Page<SerServer> page = new Page<>(pageNo, pageSize);
        // 创建时间/创建人的赋值
        IPage<SerServer> pageList = serServerService.page(page, queryWrapper);
        IPage<SerServerDpartVO> svo = new Page<>(pageNo, pageSize);
        ArrayList<SerServerDpartVO> arrayList = new ArrayList<SerServerDpartVO>();
        for(SerServer u:pageList.getRecords()) {
            SerServerDpartVO s = new SerServerDpartVO();
            SysUser user = sysUserService.getUserByName(u.getUsername());

            //集合王斌
            List<SysUserDepart> list = sysUserDepartService.departByUserId(user.getId());


            System.out.println("我看看输出的是什么：++++++++" + list);
            if(list.size() > 0){
                for (SysUserDepart depart:list) {
                    if (depart != null) {
                        String departName = "";
                        if (depart.getDepId() != null) {
                            departName = sysDepartService.getById(depart.getDepId()).getDepartName();
                            s.setDepartName(departName);
                        }
                    }
                }
            }


            s.setUsername(u.getUsername());
            System.out.println("kanknasysuserde111111111111111:++++++++++++++++++++" + u.getUsername());
            s.setVirtualserve(u.getVirtualserve());
            s.setStatus(u.getStatus());
            s.setCreateTime(u.getCreateTime());
            System.out.println("kanknasysuserde123333333331:++++++++++++++++++++" +u.getBackdecription());
            s.setBackdecription(u.getBackdecription());
            s.setId(u.getId());
            arrayList.add(s);
        }
        svo.setRecords(arrayList);
        svo.setPages(pageList.getPages());
        svo.setTotal(pageList.getTotal());
        svo.setSize(pageList.getSize());
        svo.setCurrent(pageList.getCurrent());
        log.info("查询当前页：" + pageList.getCurrent());
        log.info("查询当前页数量：" + pageList.getSize());
        log.info("查询结果数量：" + pageList.getRecords().size());
        log.info("数据总数：" + pageList.getTotal());

        result.setSuccess(true);
        result.setResult(svo);
        return result;
    }

    /**
     * 编辑
     *
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "服务配置管理-编辑")
    @ApiOperation(value = "服务配置管理-编辑")
    @PutMapping(value = "/edit")
    public Result<SerServer> edit(@RequestBody JSONObject jsonObject) {
        Result<SerServer> result = new Result<>();
        try {

            SerServer server = serServerService.getById(jsonObject.getString("id"));
            if (server == null) {
                result.error500("未找到对应实体");
            } else {
                SerServer serServer = JSON.parseObject(jsonObject.toJSONString(), SerServer.class);
                System.out.println("d:      "+serServer.getVirtualserve());
                serServer.setStatus(2);
                boolean ok = serServerService.updateById(serServer);
                result.success("修改成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    /**
     * 申请退回
     *
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "服务配置管理-退回")
    @ApiOperation(value = "服务配置管理-退回")
    @PutMapping(value = "/backServer")
    public Result<SerServer> backServer(@RequestBody JSONObject jsonObject) {
        Result<SerServer> result = new Result<>();
        try {
            String status = jsonObject.getString("status");
            System.out.println("tuihuishisha:++++++++"+status);
            SerServer server = serServerService.getById(jsonObject.getString("id"));
            SerServer serServer = JSON.parseObject(jsonObject.toJSONString(), SerServer.class);
            serServer.setStatus(0);
            boolean ok = serServerService.updateById(serServer);
                 /*   this.serServerService.update(new SerServer().setStatus(Integer.parseInt(status)),
                            new UpdateWrapper<SerServer>().lambda().eq(SerServer::getId, ids));*/
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败" + e.getMessage());
        }
        result.success("操作成功!");
        return result;

    }


    /**
     * 申请虚拟机添加
     *
     * @param server
     * @return
     */
    @AutoLog(value = "虚拟机服务-添加")
    @ApiOperation(value = "虚拟机服务-添加")
    @PostMapping(value = "/add")
    public Result<SerServer> add(@RequestBody SerServer server) {

        Result<SerServer> result = new Result<SerServer>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        /*    System.out.println("shuju+++++++++++++"+username);*/
        try {
            List<SerServer> list = serServerService.list();
            System.out.println("看看登录的用户是谁：++++++++++"+sysUser.getUsername());
        /*    String username = serServerService.selectname(sysUser.getUsername());*/

       /*     System.out.println("kanyikan :++++++"+username);*/
           /* if (!(sysUser.getUsername().equalsIgnoreCase(username))){*/
                server.setUsername(sysUser.getUsername());
                server.setStatus(1);
                System.out.println("看一看添加成功是什么：++++++++" + server.getUsername() + server.getVirtualserve());
                serServerService.save(server);
                System.out.println("看一看添加成功是什么：++++++++" + server.getUsername() + server.getVirtualserve());
                result.success("添加成功！");

         /*   }else {
                result.setMessage("数据已存在");
            }*/

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 查询全部虚拟机服务
     *
     * @return
     */
    @GetMapping(value = "/serverall")
    @ResponseBody
    public Result<List<SerVirtual>> serverall() {
        Result<List<SerVirtual>> result = new Result<>();
        System.out.println("kanyikan+++++++++++"+result);
        List<SerVirtual> list = serVirtualService.list();
        System.out.println("gggggggggggg:++++++++++"+list);
        if (list.isEmpty()) {
            result.error500("未找到虚拟机镜像信息");
        } else {
            result.setResult(list);
            result.setSuccess(true);
        }
        return result;
    }
    /**
     * 获取当前用户名称
     *
     * @return
     */
    @GetMapping(value = "/loginuser")
    @ResponseBody
    public Result<String> loginuser() {
        // 生成token
       /* SysLoginModel sysLoginModel=new SysLoginModel();
        String username = sysLoginModel.getUsername();
        String token = JwtUtil.sign(username);
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);*/
        Result<String> result = new Result<>();
        System.out.println("kanaknaknaan:++"+result);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println("kanyikan:++++++++++++++"+sysUser);
        System.out.println("输出一下数据是什么：++++++++==========="+sysUser.getUsername());
        String user=sysUser.getUsername();
        result.setResult(user);
        result.setSuccess(true);
        return result;
    }



    /**
     * @param server
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     * @功能：查询申请服务列表-当前用户
     */
    @AutoLog(value = "服务管理-分页查询申请服务记录-当前用户")
    @ApiOperation(value = "服务管理-分页查询申请服务记录-当前用户")
    @GetMapping(value = "/mylist")
    public Result<IPage<SerServerDpartVO>> mylist(SerServer server, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        server.setUsername(sysUser.getUsername());
        Result<IPage<SerServerDpartVO>> result = new Result<>();
        QueryWrapper<SerServer> queryWrapper = QueryGenerator.initQueryWrapper(server, req.getParameterMap());
        Page<SerServer> page = new Page<>(pageNo, pageSize);
        // 创建时间/创建人的赋值
        IPage<SerServer> pageList = serServerService.page(page, queryWrapper);
        IPage<SerServerDpartVO> svo = new Page<>(pageNo, pageSize);
        ArrayList<SerServerDpartVO> arrayList = new ArrayList<SerServerDpartVO>();
        for(SerServer u:pageList.getRecords()) {
            SerServerDpartVO s = new SerServerDpartVO();
            SysUser user = sysUserService.getUserByName(u.getUsername());

//            System.out.println("我看看输出的是什么：++++++++" + depart);

            List<SysUserDepart> list  = sysUserDepartService.departByUserId(user.getId());

            if(list.size() > 0){
                for (SysUserDepart depart:list) {
                    if (depart != null) {
                        String departName = "";
                        if (depart.getDepId() != null) {
                            departName = sysDepartService.getById(depart.getDepId()).getDepartName();
                            s.setDepartName(departName);
                        }
                    }
                }
            }

            s.setUsername(u.getUsername());
            System.out.println("kanknasysuserde111111111111111:++++++++++++++++++++" + u.getUsername());
            s.setVirtualserve(u.getVirtualserve());
            s.setStatus(u.getStatus());
            s.setCreateTime(u.getCreateTime());
            s.setId(u.getId());
            System.out.println("kanknasysuserde111111111111111:++++++++++++++++++++" + u.getBackdecription());
            s.setBackdecription(u.getBackdecription());
            arrayList.add(s);
        }
        svo.setRecords(arrayList);
        svo.setPages(pageList.getPages());
        svo.setTotal(pageList.getTotal());
        svo.setSize(pageList.getSize());
        svo.setCurrent(pageList.getCurrent());
        log.info("查询当前页：" + pageList.getCurrent());
        log.info("查询当前页数量：" + pageList.getSize());
        log.info("查询结果数量：" + pageList.getRecords().size());
        log.info("数据总数：" + pageList.getTotal());

        result.setSuccess(true);
        result.setResult(svo);
        return result;
    }

    /**
     * 查询全部服务状态列表
     *
     * @return
     */
    @GetMapping(value = "/statusall")
    public Result<List<SerServer>> statusall() {
        Result<List<SerServer>> result = new Result<>();
        List<SerServer> list = serServerService.list();
        System.out.println("看看服务状态的全部信息:+++++++++"+list);
        if (list.isEmpty()) {
            result.error500("未找到服务状态信息");
        } else {
            result.setResult(list);
            result.setSuccess(true);
        }
        return result;
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "服务管理-通过id删除")
    @ApiOperation(value = "服务管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<SerServer> delete(@RequestParam(name = "id", required = true) String id) {
        Result<SerServer> result = new Result<>();
        SerServer server = serServerService.getById(id);
        if (server == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = serServerService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

    /*
     * 申请停止云主机
     * */
    @AutoLog(value = "跳转zstack")
    @ApiOperation(value = "跳转zstack")
    @GetMapping(value = "allocation")
    @ResponseBody
    public Result allocation() throws InterruptedException {
//设置webdriver驱动的位置
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
        WebDriver webDriver = new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.navigate().to("http://192.168.5.139:5000");
        Thread.sleep(1000);
//定位到用户名输入框
        WebElement username = webDriver.findElement(By.xpath("//div[@id=\"account-name\"]//input[@type=\"text\"]"));
        //定位到密码输入框
        WebElement password = webDriver.findElement(By.xpath("//div[@id=\"account-password\"]//input[@type=\"password\"]"));
//输入用户名
        username.sendKeys("admin");
//输入密码
        password.sendKeys("123456");
        Thread.sleep(1000);
        WebElement login = webDriver.findElement(By.xpath("//div[@id=\"account-login-button\"]"));
        login.click();
        Thread.sleep(5000);
//登陆后等待5s让js等异步内容加载完成，最后输出页面html
        System.out.println(webDriver.getPageSource());
        Result result=new Result();
        result.setResult(webDriver.getPageSource());
        return result;
    }

}
